<template>
  <div class="measure-tools" @click.stop>
    <div class="measure-buttons">
      <ElButton 
        type="primary" 
        size="small" 
        plain
        :disabled="!hasMap"
        :class="{ active: measureType === 'distance' }"
        @click="startMeasure('distance')"
      >
        测距
      </ElButton>
      <ElButton 
        type="warning" 
        size="small" 
        plain
        :disabled="!hasMap"
        :class="{ active: measureType === 'area' }"
        @click="startMeasure('area')"
      >
        测面积
      </ElButton>
      <ElButton 
        v-if="isDrawing" 
        type="danger" 
        size="small"
        @click="endMeasure"
      >
        结束测量
      </ElButton>
      <ElButton 
        type="info" 
        size="small"
        plain
        @click="clearMeasurement"
      >
        清除测量
      </ElButton>
    </div>
    <div v-if="measureType && isDrawing" class="measure-status">
      测量中: {{ measureType === 'distance' ? '距离' : '面积' }}
    </div>
    <div v-if="hasError" class="measure-error">
      {{ errorMsg }}
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import { ElButton } from 'element-plus'
import { useMeasureStore } from '@/stores/modules/measure'
import { useMapStore } from '@/stores/modules/map'

// 定义props
const props = defineProps({
  map: {
    type: Object,
    required: true
  },
  measureTools: {
    type: Object,
    required: true
  }
})

const measureStore = useMeasureStore()
const mapStore = useMapStore()

// 使用store中的状态
const measureType = computed(() => measureStore.measureType)
const isDrawing = computed(() => measureStore.isDrawing)
const hasError = computed(() => measureStore.hasError)
const errorMsg = computed(() => measureStore.errorMsg)

// 地图实例检查
const hasMap = computed(() => !!props.map)

// 监听地图实例变化
watch(() => props.map, (newMap) => {
  console.log('地图实例已更新:', !!newMap)
  if (newMap) {
    console.log('地图实例类型:', typeof newMap)
    console.log('地图实例方法:', Object.keys(newMap).filter(k => typeof newMap[k] === 'function').slice(0, 5))
  }
}, { immediate: true })

// 监听测量工具实例变化
watch(() => props.measureTools, (newTools) => {
  console.log('测量工具实例已更新:', !!newTools)
  if (newTools) {
    console.log('测量工具实例类型:', typeof newTools)
    console.log('测量工具实例方法:', Object.keys(newTools).filter(k => typeof newTools[k] === 'function').slice(0, 5))
  }
}, { immediate: true })

// 开始测量
function startMeasure(type) {
  console.log('开始测量:', type)
  console.log('地图实例状态:', !!props.map)
  console.log('测量工具实例状态:', !!props.measureTools)
  
  if (!props.map) {
    console.error('地图未初始化')
    measureStore.setError(true, '地图未初始化')
    return
  }
  
  if (!props.measureTools) {
    console.error('测量工具未初始化')
    measureStore.setError(true, '测量工具未初始化')
    return
  }
  
  try {
    measureStore.setMeasureType(type)
    measureStore.setDrawing(true)
    measureStore.setError(false)
    
    // 调用测量工具的初始化方法
    if (typeof props.measureTools.initMap === 'function') {
      props.measureTools.initMap(props.map)
    }
    
    // 设置统一的测量线宽度，无论是2D还是3D模式
    const is3DMode = props.map.getView().getProjection().getCode() === 'EPSG:4326';
    console.log('当前地图模式:', is3DMode ? '3D模式' : '2D模式');
    
    // 统一使用相同的线宽
    if (typeof props.measureTools.setLineWidth === 'function') {
      props.measureTools.setLineWidth(1) // 统一使用较细的线宽
      console.log('设置统一线宽为1');
    }
    
    // 调用测量工具的测量方法
    if (typeof props.measureTools[`measure${type.charAt(0).toUpperCase() + type.slice(1)}`] === 'function') {
      props.measureTools[`measure${type.charAt(0).toUpperCase() + type.slice(1)}`]()
    }
    
    console.log('测量已开始:', type)
  } catch (error) {
    console.error('开始测量时出错:', error)
    measureStore.setError(true, error.message || '开始测量失败')
  }
}

// 结束测量
function endMeasure() {
  console.log('结束测量');
  try {
    if (props.measureTools && typeof props.measureTools.stopMeasure === 'function') {
      const result = props.measureTools.stopMeasure();
      console.log('测量结束结果:', result);
      
      // 无论结果如何，都重置状态
      measureStore.setDrawing(false);
      measureStore.setMeasureType(null);
      
      // 确保地图视图已刷新
      if (props.map) {
        try {
          props.map.render();
          console.log('地图视图已刷新');
          
          // 添加一个短暂延迟，确保所有状态都被正确应用
          setTimeout(() => {
            try {
              // 移除所有绘图相关的DOM元素
              const drawElements = document.querySelectorAll('.ol-draw, .ol-draw-handle');
              drawElements.forEach(el => {
                if (el && el.parentNode) {
                  el.parentNode.removeChild(el);
                }
              });
              
              // 再次刷新地图视图
              props.map.render();
              console.log('延迟后再次刷新地图视图');
            } catch (e) {
              console.warn('延迟清理失败:', e);
            }
          }, 100);
        } catch (e) {
          console.warn('刷新地图视图失败:', e);
        }
      }
      
      console.log('测量已结束');
      return result;
    } else {
      console.warn('结束测量方法不可用');
      measureStore.setDrawing(false);
      measureStore.setMeasureType(null);
      return false;
    }
  } catch (error) {
    console.error('结束测量时出错:', error);
    measureStore.setError(true, error.message || '结束测量失败');
    measureStore.setDrawing(false);
    measureStore.setMeasureType(null);
    return false;
  }
}

// 清除测量
function clearMeasurement() {
  console.log('清除所有测量要素');
  try {
    if (props.measureTools && typeof props.measureTools.clearAll === 'function') {
      const result = props.measureTools.clearAll();
      console.log('清除测量要素结果:', result ? '成功' : '失败');
      
      // 清除测量状态
      if (result) {
        measureStore.clearMeasureResults();
        measureStore.resetMeasureState();
        measureStore.setError(false, '');
      }
      
      // 确保地图视图已刷新
      if (props.map) {
        try {
          props.map.render();
          console.log('地图视图已刷新');
          
          // 添加一个短暂延迟，确保所有状态都被正确应用
          setTimeout(() => {
            try {
              // 移除所有绘图相关的DOM元素
              const drawElements = document.querySelectorAll('.ol-draw, .ol-draw-handle');
              drawElements.forEach(el => {
                if (el && el.parentNode) {
                  el.parentNode.removeChild(el);
                }
              });
              
              // 再次刷新地图视图
              props.map.render();
              console.log('延迟后再次刷新地图视图');
            } catch (e) {
              console.warn('延迟清理失败:', e);
            }
          }, 100);
        } catch (e) {
          console.warn('刷新地图视图失败:', e);
        }
      }
      
      console.log('测量已清除');
      return result;
    } else {
      console.warn('清除测量方法不可用');
      measureStore.clearMeasureResults();
      measureStore.resetMeasureState();
      return false;
    }
  } catch (error) {
    console.error('清除测量时出错:', error);
    measureStore.setError(true, error.message || '清除测量失败');
    measureStore.clearMeasureResults();
    measureStore.resetMeasureState();
    return false;
  }
}

// 组件挂载时初始化
onMounted(() => {
  console.log('MeasureTools组件已挂载')
  console.log('地图实例状态:', !!props.map)
  console.log('测量工具实例状态:', !!props.measureTools)
  
  if (props.map) {
    console.log('地图实例类型:', typeof props.map)
    console.log('地图实例方法:', Object.keys(props.map).filter(k => typeof props.map[k] === 'function').slice(0, 5))
  }
  
  if (props.measureTools) {
    console.log('测量工具实例类型:', typeof props.measureTools)
    console.log('测量工具实例方法:', Object.keys(props.measureTools).filter(k => typeof props.measureTools[k] === 'function').slice(0, 5))
  }
})

// 组件卸载时清理
onBeforeUnmount(() => {
  console.log('MeasureTools组件即将卸载')
  measureStore.resetMeasureState()
})
</script>

<style scoped>
.measure-tools {
  position: absolute;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  gap: 8px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  padding: 8px;
  min-width: 120px;
  pointer-events: auto !important;
}

.measure-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
  pointer-events: auto !important;
}

.measure-buttons .active {
  background-color: #409eff;
  color: white;
}

.measure-buttons button {
  position: relative;
  z-index: 1001;
  pointer-events: auto !important;
  cursor: pointer !important;
}

.measure-status {
  font-size: 12px;
  color: #409eff;
  padding: 3px 0;
  text-align: center;
  pointer-events: auto !important;
}

.measure-error {
  font-size: 12px;
  color: #f56c6c;
  padding: 3px 0;
  text-align: center;
  pointer-events: auto !important;
}

/* 确保测量提示在3D模式下可见 */
:deep(.ol-tooltip-measure) {
  z-index: 1001;
  pointer-events: none !important;
}

:deep(.ol-tooltip-static) {
  z-index: 1001;
  pointer-events: none !important;
}

/* 针对3D模式下的特殊处理 */
:deep(.ol-viewport) {
  z-index: 1000;
  pointer-events: auto !important;
}

/* 确保按钮可点击 */
:deep(.el-button) {
  pointer-events: auto !important;
  cursor: pointer !important;
  position: relative;
  z-index: 1002 !important;
}
</style> 